from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.conf import settings
from common.models import AuthUser
from adminapi.utils.jwt_utils import verify_token
from adminapi.utils.response import success_response, error_response
from adminapi.utils.pagination import paginate_queryset
from adminapi.utils.log_utils import log_operation
import json
from datetime import datetime

@require_http_methods(["GET"])
def user_list(request):
    """获取用户列表"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        user_id = verify_token(token)
        if not user_id:
            return error_response('无效的token', 401)
        
        # 获取分页参数
        page = int(request.GET.get('page', 1))
        size = int(request.GET.get('size', 10))
        
        # 获取用户列表
        queryset = AuthUser.objects.all().order_by('-created_at')
        result = paginate_queryset(queryset, page, size)
        
        # 格式化数据
        user_list = []
        for user in result['items']:
            user_list.append({
                'id': user.id,
                'nickname': user.nickname,
                'avatar': user.avatar,
                'phone': user.phone,
                'is_active': user.is_active,
                'is_vip': user.is_vip,
                'vip_expire_time': user.vip_expire_time.strftime('%Y-%m-%d %H:%M:%S') if user.vip_expire_time else None,
                'created_at': user.created_at.strftime('%Y-%m-%d %H:%M:%S')
            })
        
        return success_response({
            'list': user_list,
            'total': result['total'],
            'page': result['page'],
            'size': result['size'],
            'pages': result['pages']
        })
    except Exception as e:
        return error_response(f'获取用户列表失败：{str(e)}')

@require_http_methods(["GET"])
def user_detail(request, user_id):
    """获取用户详情"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 查找用户
        try:
            user = AuthUser.objects.get(id=user_id)
        except AuthUser.DoesNotExist:
            return error_response('未找到指定的用户', 404)
        
        # 格式化数据
        user_data = {
            'id': user.id,
            'nickname': user.nickname,
            'avatar': user.avatar,
            'phone': user.phone,
            'is_active': user.is_active,
            'is_vip': user.is_vip,
            'vip_expire_time': user.vip_expire_time.strftime('%Y-%m-%d %H:%M:%S') if user.vip_expire_time else None,
            'created_at': user.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        return success_response(user_data)
    except Exception as e:
        return error_response(f'获取用户详情失败：{str(e)}')

@require_http_methods(["POST"])
def user_create(request):
    """创建用户"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 解析请求数据
        data = json.loads(request.body)
        nickname = data.get('nickname', '')
        phone = data.get('phone', '')
        password = data.get('password', '')
        is_active = data.get('is_active', True)
        is_vip = data.get('is_vip', False)
        
        if not nickname or not phone or not password:
            return error_response('参数错误', 400)
        
        # 检查手机号是否已存在
        if AuthUser.objects.filter(phone=phone).exists():
            return error_response('手机号已存在', 400)
        
        # 创建用户
        user = AuthUser.objects.create(
            nickname=nickname,
            phone=phone,
            is_active=is_active,
            is_vip=is_vip
        )
        user.set_password(password)
        user.save()
        
        # 记录操作日志
        log_operation(admin_id, 'create_user', f'创建用户：{user.nickname}')
        
        return success_response({
            'id': user.id,
            'nickname': user.nickname,
            'phone': user.phone,
            'is_active': user.is_active,
            'is_vip': user.is_vip,
            'created_at': user.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    except json.JSONDecodeError:
        return error_response('无效的JSON数据', 400)
    except Exception as e:
        return error_response(f'创建用户失败：{str(e)}')

@require_http_methods(["PUT"])
def user_update(request, user_id):
    """更新用户"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 查找用户
        try:
            user = AuthUser.objects.get(id=user_id)
        except AuthUser.DoesNotExist:
            return error_response('未找到指定的用户', 404)
        
        # 解析请求数据
        data = json.loads(request.body)
        nickname = data.get('nickname', user.nickname)
        phone = data.get('phone', user.phone)
        password = data.get('password', '')
        is_active = data.get('is_active', user.is_active)
        is_vip = data.get('is_vip', user.is_vip)
        
        # 检查手机号是否已被其他用户使用
        if phone != user.phone and AuthUser.objects.filter(phone=phone).exists():
            return error_response('手机号已存在', 400)
        
        # 更新用户信息
        user.nickname = nickname
        user.phone = phone
        user.is_active = is_active
        user.is_vip = is_vip
        if password:
            user.set_password(password)
        user.save()
        
        # 记录操作日志
        log_operation(admin_id, 'update_user', f'更新用户：{user.nickname}')
        
        return success_response({
            'id': user.id,
            'nickname': user.nickname,
            'phone': user.phone,
            'is_active': user.is_active,
            'is_vip': user.is_vip,
            'created_at': user.created_at.strftime('%Y-%m-%d %H:%M:%S')
        })
    except json.JSONDecodeError:
        return error_response('无效的JSON数据', 400)
    except Exception as e:
        return error_response(f'更新用户失败：{str(e)}')

@require_http_methods(["DELETE"])
def user_delete(request, user_id):
    """删除用户"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        admin_id = verify_token(token)
        if not admin_id:
            return error_response('无效的token', 401)
        
        # 查找用户
        try:
            user = AuthUser.objects.get(id=user_id)
        except AuthUser.DoesNotExist:
            return error_response('未找到指定的用户', 404)
        
        # 删除用户
        user.delete()
        
        # 记录操作日志
        log_operation(admin_id, 'delete_user', f'删除用户：{user.nickname}')
        
        return success_response('用户删除成功')
    except Exception as e:
        return error_response(f'删除用户失败：{str(e)}') 